class Project < ActiveRecord::Base
  validates_presence_of :name, :fee, :contract_date
  #validates_presence_of :contacts
  #validates_associated :contacts
  validates_presence_of :currency_rate, :if => :is_foreign_currency,:message => 'is required for USD or EURO projects'

  has_many :activities
  has_many :phases, :through => :activities

  has_many :tasks
  has_many :documents
  has_many :contacts
  has_many :users, :through=> :members_projects
  has_many :notes


  def is_foreign_currency
    ['USD','EUR'].include?(currency)
  end
  
  def self.find_all_active
    Project.find(:all, :conditions => ["is_active = ?", true])
  end
  
  def self.find_all_archived
    Project.find(:all, :conditions => ["is_active = ?", false])
  end

  #Finds total worked in this project.
  def total_working_hours
    total_worked_hours=0
    activities.each do |actvty|
      total_worked_hours+=actvty.total_working_hours
    end
    total_worked_hours
  end

  #Finds total worked in this project.
  def total_revision_hours
    total_worked_hours=0
    activities.each do |actvty|
      total_worked_hours+=actvty.total_time_spent_for_revision
    end
    total_worked_hours
  end
  def estimated_hours
    "Not given yet"
  end

  def revision_percent_in_total_working_hours_p
    percent = 0
    percent = (total_revision_hours * 100 / total_working_hours)  if total_working_hours > 0
    percent
  end
  def members
    User.find_by_sql("select u.* from users u, members_projects up where u.id = up.user_id and up.project_id = #{self.id}")
  end

  def collection_amount_total (in_project_currency=false)
    sum=0
    activities.each { |activity|
      sum+=activity.collection_amount_total(in_project_currency)
    }
    sum
      
  end

  def total_working_cost_p
    total_cost = tasks.collect { |a| a.total_working_cost}.sum
    total_cost
  end
  def profit_loss_p
    collection_amount_total - total_working_cost_p
  end


  def uncollected_amount
    fee - collection_amount_total(true)
  end
end